package cn.com.lyb.flink;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * nc -lk 1234  启动一个socket
 * DataStream 读取socket数据
 */

public class StreamSocketWordCount {

    public static void main(String[] args) throws Exception {
        // 创建环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        // 监听socket
        DataStreamSource<String> socketDS = env.socketTextStream("172.32.1.6", 1234);
        //
        SingleOutputStreamOperator<Tuple2<String, Integer>> sum = socketDS.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public void flatMap(String value, Collector<Tuple2<String, Integer>> out) throws Exception {
                // 通过采集器向下游发送数据
                out.collect(Tuple2.of(value, 1));
            }

        }).keyBy(new KeySelector<Tuple2<String, Integer>, Object>() {
            @Override
            public Object getKey(Tuple2<String, Integer> stringIntegerTuple2) throws Exception {
                return stringIntegerTuple2.f0;
            }
        }) // 聚合
                .sum(1); // 求和
        // 输出
        sum.print();
        // 执行，有异常
        env.execute();
    }
}
